import { useEffect, useState } from "react";
import { View } from "@tarojs/components";
import {
  Layout,
  WithMargins,
  C06HeroSlideBanner,
  C07MainTitleArea,
  C10TabSection,
  C12Recommendation,
  C13BottomDock,
  C14Table,
} from "@/components";
import { convertTimeToAmPm, formatDateString } from "@/utils";
import useDetailPageData from "@/hooks/useDetailPageData";
import { ModalTypes, useApplicationInfo } from "@/store/applicationDataContext";
import { colors } from "@/data/shared/colors";
import { ApiItemTypeMapping } from "@/data/shared/entityShapes";
import { apiItemTypeMapping } from "@/utils/apiMapping";
import { ApiTalkTypes, TalkShape } from "@/data/talks/talkTypes";
import { navigateTo, switchTab } from "@/utils/navigation";
import { generateKey, getUserData, useUserInfo } from "@/store/userDataContext";
import { useAuth } from "@/store/authContext";
import { BottomDockButtonShape } from "@/components/c13-BottomDock";
import { sendAction, ActionNames, ActionKeys } from "@/utils/tracking";
import { useEventListSplit } from "@/hooks/useEventListSplit";
import style from "./index.module.scss";
import Taro from "@tarojs/taro";

export default function TalkDetail() {
  const [talkData, liked, preview] = useDetailPageData("talk") as [
    TalkShape,
    Boolean,
    Boolean
  ];
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { dispatchAuthAction } = useAuth();
  const { userData } = userInfoState;
  const { dispatch } = useApplicationInfo();
  const [userName, setUserName] = useState("");
  const [shouldRecall, setShouldRecall] = useState(false);

  // For talks to populate sharing
  useEffect(() => {
    if (talkData) {
      dispatch({
        type: "SET_SHARE_DATA",
        data: {
          text: talkData.name,
          imagePath: talkData.sharePoster
            ? talkData.sharePoster
            : talkData.cover,
        },
      });

      sendAction(ActionNames.TalkDetailImpression, {
        [ActionKeys.TalkType]: talkData.talkTypeName,
        [ActionKeys.TalkName]: talkData.name,
      });
    }
  }, [talkData]);

  const trackBookingCtaAction = () => {
    sendAction(ActionNames.TalkDetailReserveClick, {
      [ActionKeys.TalkType]: talkData.talkTypeName,
      [ActionKeys.TalkName]: talkData.name,
      [ActionKeys.TalkTime]: talkData.schedulingStartTime,
      [ActionKeys.TalkDuration]: talkData.duration,
      [ActionKeys.TalkLanguage]: Object.values(talkData.optionalLanguage)[0],
      [ActionKeys.TalkPlatform]: talkData.viewingPlatformName,
    });
  };

  const trackOfflineBookingAction = (actionName) => {
    sendAction(actionName, {
      [ActionKeys.TalkType]: talkData.talkTypeName,
      [ActionKeys.TalkName]: talkData.name,
      [ActionKeys.TalkDuration]: talkData.duration,
      [ActionKeys.TalkLanguage]: Object.values(talkData.optionalLanguage)[0],
      [ActionKeys.TalkPlatform]: talkData.viewingPlatformName,
      [ActionKeys.TalkDate]: talkData.schedulingDate,
    });
  };

  const updateBooking = () => {
    if (talkData) {
      trackOfflineBookingAction(
        ActionNames.OfflineConversationDetailReserveAgainClick
      );
    }
    bookEvents(true);
  };

  const eventRecSplit = useEventListSplit(talkData);

  const bookEvents = async (isUpdate?: boolean) => {
    if (talkData) {
      talkData.handlePlaceOrder({
        query: {
          type: ApiItemTypeMapping.Talk,
          preOrderDetail: {
            mainId: talkData.id,
            count: 1,
            scheduleLings: [
              {
                courseId: talkData.id,
                scheduleId: talkData.schedulingId,
              },
            ],
          },
          preOrderType: "buyNow",
        },
      });

      !isUpdate && trackBookingCtaAction();
    }
  };

  const lineUp = async () => {
    if (talkData) {
      const result = await talkData.handleLineUp({
        query: {
          mainId: talkData.id,
          type: ApiItemTypeMapping.Talk,
        },
        authDispatch: dispatchAuthAction,
      });
      if (result) {
        navigateTo(`pages/user-waiting-list/index`);
      }
    }
  };

  const goLive = async () => {
    if (userName) {
      setShouldRecall(false);
      if (talkData && talkData.isAppointment && talkData.liveBroadLink) {
        const regex_emoji =
          /(\p{Emoji_Presentation}|\p{Extended_Pictographic})/gu;
        const key = await generateKey({
          query: { id: talkData.id },
        });
        const liveLink = `${talkData.liveBroadLink}?k=${key}&email=${encodeURI(
          userName.replace(regex_emoji, "")
        )}@lecole.com&name=${encodeURI(userName)}`;
        // const liveLink = `https://live6.vhall.com/webinar/inituser/479553835?k=${key}&name=${encodeURI(userName)}` // test
        dispatchUserDataAction({
          type: "LIVE_LINK",
          data: liveLink,
        });
        navigateTo(`pages/web-view-container/index?mode=live`);
      } else {
        bookEvents();
      }
    } else {
      const userInfo = await getUserData(dispatchUserDataAction, userData!, {
        authDispatch: dispatchAuthAction,
      });
      if (userInfo) {
        setShouldRecall(true);
      }
    }

    sendAction(ActionNames.OnlineTalkBookDetailClick, {
      [ActionKeys.OnlineTalkName]: talkData?.name,
      [ActionKeys.OnlineTalkStatus]: talkData?.liveBroadcastStatus!,
    });
  };

  useEffect(() => {
    if (userData?.userInfo.nickName && shouldRecall) {
      goLive();
      setUserName(userData?.userInfo.nickName);
      setShouldRecall(false);
    }
  }, [userData?.userInfo.nickName, userName, shouldRecall]);

  const DEFAULT_PRIMARY_CTA_BOOK = {
    //0
    cb: bookEvents,
    text: "预约讲座",
  };
  const DEFAULT_SECONDARY_CTA_NULL = null;

  const SHOW_MODAL = {
    //1
    cb: () => {
      trackOfflineBookingAction(ActionNames.OfflineShowId);
      dispatch({ type: "SHOW_MODAL", data: ModalTypes.QR });
    },
    text: "出示预约码",
  };

  const LINE_UP = {
    //3
    cb: lineUp,
    text: "候补登记",
  };

  const GO_TO_DISCOVER = {
    //2
    cb: () => {
      switchTab("pages/discover/index");
    },
    text: "探索更多",
  };

  // 跳转视频号
  const GO_TO_CHANNELID = {
    //
    cb: () => {
      // 跳转视频号
      Taro.openChannelsActivity({
        finderUserName: talkData.channelsId,
        feedId: talkData.videoId
      })

    },
    text: "探索更多",
  }

  const [primaryCta, setPrimaryCta] = useState<BottomDockButtonShape>(
    DEFAULT_PRIMARY_CTA_BOOK
  );
  const [secondaryCta, setSecondaryCta] =
    useState<BottomDockButtonShape | null>(DEFAULT_SECONDARY_CTA_NULL);

  useEffect(() => {
    if (talkData) {
      setPrimaryCta(DEFAULT_PRIMARY_CTA_BOOK);
      setSecondaryCta(DEFAULT_SECONDARY_CTA_NULL);
      if (talkData.isDeleted || !talkData.status) {
        if (talkData.channelsId) {
          setPrimaryCta(GO_TO_CHANNELID);
        } else {
          setPrimaryCta(GO_TO_DISCOVER);
        }
      } else {
        switch (talkData.talkType) {
          case ApiTalkTypes.Online:
            if (talkData.channelsId) {
              setPrimaryCta(GO_TO_CHANNELID);
            } else {
              setPrimaryCta({
                cb: () => {
                  trackBookingCtaAction();
                  navigateTo(
                    `pages/web-view-container/index?link=${talkData.link}&name=${talkData.name}`
                  );
                },
                disabled: !talkData.link,
                text: "预约直播",
              });
            }

            break;
          case ApiTalkTypes.Offline:
            if (!talkData.totalSeatsLeftForAllScheduledTalk) {
              if (talkData.orderQuantityToBeWrittenOff === 0) {
                if (talkData.completedOrderQuantity! > 0) {
                  setSecondaryCta(LINE_UP);
                  if (talkData.channelsId) {
                    setPrimaryCta(GO_TO_CHANNELID);
                  } else {
                    setPrimaryCta(GO_TO_DISCOVER);
                  }
                } else {
                  setPrimaryCta(LINE_UP);
                }
              } else {
                setPrimaryCta(SHOW_MODAL);
                setSecondaryCta(LINE_UP);
              }
            } else {
              if (talkData.isAppointment) {
                setPrimaryCta(SHOW_MODAL);
                // Rebook
                setSecondaryCta({
                  cb: updateBooking,
                  text: "重新预约",
                });

                if (
                  // Again unclear if both needed
                  talkData.completedOrderQuantity! > 0 &&
                  talkData.orderQuantityToBeWrittenOff === 0
                ) {
                  if (talkData.channelsId) {
                    setPrimaryCta(GO_TO_CHANNELID);
                  } else {
                    setPrimaryCta(GO_TO_DISCOVER);
                  }
                }
              }
            }
            break;

          default:
            break;
        }
      }
    }
  }, [talkData]);

  const isOnline = talkData?.talkType === ApiTalkTypes.Online;
  const remainingSeatSection = isOnline
    ? []
    : [
      {
        key: "空闲名额",
        value: `${talkData?.remainingSeatCount}个席位`,
      },
    ];

  return (
    <Layout>
      <View className={style.wrapper}>
        {talkData && (
          <>
            {!!talkData?.carouselMap.length && (
              <C06HeroSlideBanner
                images={talkData.carouselMap}
                themeColor={colors.colorConversation}
                videoSrc={
                  talkData.mainPictureVideo ? talkData.mainPictureVideo : null
                }
              />
            )}

            {talkData.schedulingId && (
              <WithMargins>
                <C07MainTitleArea
                  categoryName={talkData.talkTypeName}
                  themeColor={colors.colorConversation}
                  price={talkData.price}
                  heading={talkData.name}
                  description={talkData.introduction}
                />

                <C14Table
                  rowData={[
                    {
                      key: "讲座时间",
                      value:
                        talkData.schedulingDate &&
                        formatDateString(talkData.schedulingDate),
                      secondRowHighlighted:
                        talkData.schedulingStartTime &&
                        `${convertTimeToAmPm(
                          talkData.schedulingStartTime
                        )} - ${convertTimeToAmPm(talkData.schedulingEndTime)}`,
                    },
                    {
                      key: "讲座时长",
                      value: talkData.duration || "",
                    },
                    {
                      key: "可选语言",
                      value:
                        talkData.optionalLanguage &&
                        Object.values(talkData.optionalLanguage).join(", "),
                    },
                    {
                      key: isOnline ? "观看平台" : "地址",
                      value: isOnline
                        ? talkData.viewingPlatformName
                        : talkData.courseAddress.courseAddress,
                      secondRowHighlighted: isOnline
                        ? null
                        : talkData.courseAddress.courseAddressInfo,
                    },
                    ...remainingSeatSection,
                  ]}
                />
              </WithMargins>
            )}

            {/* Tabbed view */}
            <C10TabSection tabContent={talkData.talkInfo.details} />

            {!!eventRecSplit.courses.length && (
              <C12Recommendation
                recommendationTitle="课程推荐"
                cardData={eventRecSplit.courses.map((relatedEvent) => ({
                  cardId: relatedEvent.aboutId,
                  imagePath: relatedEvent.sharePoster || relatedEvent.cover,
                  title: relatedEvent.name,
                  tag: relatedEvent.typeName,
                  cost: relatedEvent.price,
                  type: "course-card",
                  themeColor: relatedEvent.labelColor,
                  redirect: apiItemTypeMapping[relatedEvent.typeCourse],
                }))}
              />
            )}
            {(!!talkData.shopRecommendations?.length ||
              !!eventRecSplit.otherEvents.length) && (
                <C12Recommendation
                  recommendationTitle="您也可能喜欢"
                  type="mixed"
                  cardData={[
                    ...(talkData.shopRecommendations ?? []),
                    ...eventRecSplit.otherEvents,
                  ].map((recommendItem) => ({
                    cardId: recommendItem.aboutId,
                    imagePath: recommendItem.sharePoster || recommendItem.cover,
                    title: recommendItem.name,
                    cost: recommendItem.price,
                    type: "recommendation-mixed",
                    themeColor: recommendItem.labelColor,
                    redirect: apiItemTypeMapping[recommendItem.typeCourse],
                  }))}
                />
              )}
          </>
        )}
      </View>
      {talkData && !preview && (
        <C13BottomDock
          onPrimaryClick={primaryCta}
          onSecondaryClick={secondaryCta}
          onSaveClick={() => {
            talkData.handleFav(talkData!.id, ApiItemTypeMapping.Talk);
          }}
          liked={liked ? true : false}
        />
      )}
    </Layout>
  );
}
